package com.meishij.fragment;


import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.PtrUIHandler;
import com.chanven.lib.cptr.indicator.PtrIndicator;
import com.jash.myutils.utils.ViewUtils;
import com.meishij.R;
import com.meishij.adapter.FindMainRecyclerAdapter;
import com.meishij.entry.FindEntry;
import com.meishij.fragment.finddetail.FindCaiDanActivity;
import com.meishij.fragment.finddetail.FindRegionActivity;
import com.meishij.fragment.finddetail.FindShiCaiActivity;
import com.meishij.fragment.finddetail.FindWenZhangActivity;
import com.meishij.fragment.finddetail.FindZhuanTiActivity;
import com.meishij.server.FindServer;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


/**
 * A simple {@link Fragment} subclass.
 */
public class FindFragment extends Fragment implements View.OnClickListener {

    private static final String TAG = FindFragment.class.getSimpleName();
    private RecyclerView recycler_find_main;
    private Retrofit retrofit;
    private FindMainRecyclerAdapter findMainRecyclerAdapter;
    private TextView tv_find_faxian_region;
    private View userTrackAndRefresh;
    private PtrFrameLayout ptrFindMain;
    private ImageView iv_ptr;
    private TextView tv_ptr_notify;
    private TextView tv_ptr_time;

    private static final int HANDLER_WHAT_PRT = 1;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HANDLER_WHAT_PRT:
                    if (ptrFindMain != null) {
                        if (ptrFindMain.isRefreshing()) {
                            ptrFindMain.refreshComplete();
                        }
                    }

                    break;
            }
        }
    };


    public FindFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_find, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initRetrofit();
        requestNetData();
    }


    private void initView(View root) {
        View layout_find_faxian_region = root.findViewById(R.id.layout_find_faxian_region);
        layout_find_faxian_region.setOnClickListener(this);
        tv_find_faxian_region = (TextView) root.findViewById(R.id.tv_find_faxian_region);

        View iv_find_shicai = root.findViewById(R.id.iv_find_shicai);
        iv_find_shicai.setOnClickListener(this);
        View iv_find_caidan = root.findViewById(R.id.iv_find_caidan);
        iv_find_caidan.setOnClickListener(this);
        View iv_find_zhuanti = root.findViewById(R.id.iv_find_zhuanti);
        iv_find_zhuanti.setOnClickListener(this);
        View iv_find_wenzhang = root.findViewById(R.id.iv_find_wenzhang);
        iv_find_wenzhang.setOnClickListener(this);

        userTrackAndRefresh = root.findViewById(R.id.layout_find_tools);
        View userTrack = root.findViewById(R.id.iv_find_userTrack);
        userTrack.setOnClickListener(this);
        View refresh = root.findViewById(R.id.iv_find_refresh);
        refresh.setOnClickListener(this);

        recycler_find_main = (RecyclerView) root.findViewById(R.id.recycler_find_main);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
        recycler_find_main.setLayoutManager(layoutManager);
        findMainRecyclerAdapter = new FindMainRecyclerAdapter(getContext(), null);
        recycler_find_main.setAdapter(findMainRecyclerAdapter);
        recycler_find_main.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                // 向上滑动 :dy > 0
                // 向下滑动 :dy < 0
                if (dy > 0) {
                    userTrackAndRefresh.setVisibility(View.INVISIBLE);
                } else {
                    userTrackAndRefresh.setVisibility(View.VISIBLE);
                }
            }
        });

        ptrFindMain = (PtrFrameLayout) root.findViewById(R.id.ptr_find_main);
        setPtr(ptrFindMain);
    }

    public void setPtr(final PtrFrameLayout ptr) {
        //下拉刷新支持时间
        //ptr.setLastUpdateTimeRelateObject(this);
        //下拉刷新一些设置 详情参考文档
        ptr.setResistance(1.7f);
        ptr.setRatioOfHeaderHeightToRefresh(1.2f);
        ptr.setDurationToClose(200);
        ptr.setDurationToCloseHeader(1000);
        ptr.setPullToRefresh(false);
        ptr.setKeepHeaderWhenRefresh(true);

        View headView = LayoutInflater.from(getContext()).inflate(R.layout.item_shihua_anim_ptr, null);
        iv_ptr = ((ImageView) headView.findViewById(R.id.iv_shihua_top_anim));
        tv_ptr_notify = ((TextView) headView.findViewById(R.id.tv_shihua_top_notify));
        tv_ptr_time = ((TextView) headView.findViewById(R.id.tv_shihua_top_time));
        ptr.setHeaderView(headView);

        // 打开页面显示刷新
        ptr.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr.autoRefresh(true);
            }
        }, 150);

        //下拉刷新
        ptr.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                requestNetData();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, content, header);
            }
        });

        //下拉刷新
        ptr.addPtrUIHandler(new PtrUIHandler() {

            private Date preUpdateTime;
            private AnimationDrawable ptrAnimation;

            @Override
            public void onUIReset(PtrFrameLayout frame) {
                if (ptrAnimation != null || ptrAnimation.isRunning()) {
                    ptrAnimation.stop();
                }
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {
                ptrAnimation = (AnimationDrawable) iv_ptr.getDrawable();
                tv_ptr_notify.setText("下拉刷新");
            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                // 获取帧动画
                ptrAnimation.start();
                tv_ptr_notify.setText("正在努力加载数据");
                handler.sendEmptyMessageDelayed(HANDLER_WHAT_PRT, 5000);
                requestNetData();
                preUpdateTime = new Date();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                if (ptrAnimation != null || ptrAnimation.isRunning()) {
                    ptrAnimation.stop();
                }
                tv_ptr_notify.setText("刷新成功");
                if (preUpdateTime != null) {
                    tv_ptr_time.setText("本次更新时间:" + new SimpleDateFormat("MM-dd HH:mm:ss").format(preUpdateTime));
                } else {
                    tv_ptr_time.setText("");
                }
                iv_ptr.setImageResource(R.drawable.anim_shihua_pull_to_refresh);
            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                //ptrFrameLayout的下拉距离
                int offsetToRefresh = frame.getOffsetToRefresh();

                //当前滑动到的Y位置
                int currentPosY = ptrIndicator.getCurrentPosY();
                //上一次滑动到的Y位置
                int lastPosY = ptrIndicator.getLastPosY();
                //Log.e("Test", "onUIPositionChange"+offsetToRefresh+"  "+currentPosY+"  "+lastPosY);
                //向上滑或者下滑的距离 不到offsetToRefresh
                if (currentPosY < offsetToRefresh && lastPosY >= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("下拉刷新");
                    }
                }//到达一定下拉滑动距离
                else if (currentPosY > offsetToRefresh && lastPosY <= offsetToRefresh) {
                    if (isUnderTouch && status == PtrFrameLayout.PTR_STATUS_PREPARE) {
                        tv_ptr_notify.setText("松开刷新");
                    }
                }
            }
        });
    }

    private void initRetrofit() {
        retrofit = new Retrofit.Builder()
                .baseUrl(FindServer.BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private void requestNetData() {
        // 当如果加载更多的时候,就不能下来刷新
        if (ptrFindMain != null && !ptrFindMain.isRefreshing() && !ptrFindMain.isLoadingMore()) {
            ptrFindMain.autoRefresh();
        }
        FindServer findServer = retrofit.create(FindServer.class);
        Call<FindEntry> call = findServer.getFindMainResult();
        call.enqueue(new Callback<FindEntry>() {
            @Override
            public void onResponse(Call<FindEntry> call, Response<FindEntry> response) {
                if (ptrFindMain != null && ptrFindMain.isRefreshing()) {
                    ptrFindMain.refreshComplete();
                }
                FindEntry findEntry = response.body();
                if (findEntry != null) {
                    ViewUtils.setTextView(tv_find_faxian_region, findEntry.getFaxian_region());
                    List<FindEntry.DiscoveryItemEntry> faxian_list = findEntry.getFaxian_list();
                    findMainRecyclerAdapter.clear();
                    findMainRecyclerAdapter.addAll(faxian_list);
                }
            }

            @Override
            public void onFailure(Call<FindEntry> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(getContext(), "网络请求失败", Toast.LENGTH_SHORT).show();
                if (ptrFindMain != null && ptrFindMain.isRefreshing()) {
                    ptrFindMain.refreshComplete();
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 100) {
            String region = data.getStringExtra("region");
            if (!TextUtils.isEmpty(region)) {
                tv_find_faxian_region.setText(region);
                Toast.makeText(getContext(), "选择城市:" + region, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.layout_find_faxian_region:
                Intent intentToRegion = new Intent(getContext(), FindRegionActivity.class);
                String region = tv_find_faxian_region.getText().toString();
                intentToRegion.putExtra("region", region);
                startActivityForResult(intentToRegion, 100);
                break;
            case R.id.iv_find_shicai:
                Intent intentToShiCai = new Intent(getContext(), FindShiCaiActivity.class);
                startActivity(intentToShiCai);
                break;
            case R.id.iv_find_caidan:
                Intent intentToCaiDan = new Intent(getContext(), FindCaiDanActivity.class);
                startActivity(intentToCaiDan);
                break;
            case R.id.iv_find_zhuanti:
                Intent intentToZhuanTi = new Intent(getContext(), FindZhuanTiActivity.class);
                startActivity(intentToZhuanTi);
                break;
            case R.id.iv_find_wenzhang:
                Intent intentToWenZhang = new Intent(getContext(), FindWenZhangActivity.class);
                startActivity(intentToWenZhang);
                break;
            case R.id.iv_find_userTrack:
                Toast.makeText(getContext(), "用户足迹", Toast.LENGTH_SHORT).show();
                break;
            case R.id.iv_find_refresh:
                recycler_find_main.scrollToPosition(0);
                requestNetData();
                break;
        }
    }
}

